/* eslint-disable default-case */
import { message } from 'antd';
import {
  getCustContList,
  getSuppContList,
  delCont,
  updateStatus,
  fetchBaseDepart,
  queryUserList,
  customerSubmit,
  getCustomerDetail,
  customerUpdateSubmit,
  getQuotationList,
  getHistoryList,
  getHistoryDetail,
  renewSubmit,
  getListByUser,
  getCustName,
  getAddCustSearch,
  getmdCustInfo,
  supplyInsert,
  suppContSubmit,
  getSuppContDetail,
  suppContUpdateSubmit,
  getSupplyHistoryList,
  getHistorySupplyDetail,
  getDownloadInfo,
  getUploadProgress,
  baUploadFile,
  sbUploadFile,
  getRespUserList,
} from '@/services/salemanage';
import { matchDict } from '@/utils/utils';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

let baSpType;
// 非常重要属性
const namespace = 'busicont';
const ModelAddEmp = {
  namespace,
  state: {
    formFieldsValue: {},
    activeKey: '1',
    tabList: [
      { itemCode: '1', itemName: '客户合同', isHas: false },
      { itemCode: '2', itemName: '供应商合同', isHas: false },
    ],
    stateMap: ['warning', 'default', 'success', 'error'],
    expandForm: false,
    pageData: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    contInfo: {}, // 客户合同回显数据
    pageQuoData: {
      // 报价单列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    historyList: [], // 客户合同 历史记录列表
    supplyInfo: {}, // 供应商合同回显数据
    supplyHistoryList: [], // 供应商合同 历史记录列表
    batchQuery: {
      // 批量上传数据
      progressPercent: 0,
    },
    resultInfo: {
      // 结果数据必传
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
      errorUrl: '/csApi/custCont/dowoloadErrorExist', // 下载错误信息地址
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    valuesArr: [
      'custId',
      'suppId',
      'contId',
      'suppContId',
      'contState',
      'serType',
      'creTime',
      'primId',
    ],
    respUserList: [],
    tempType: null,
  },
  effects: {
    // 获取客户合同列表
    *fetchCustContList({ payload }, { call, put }) {
      const response = yield call(getCustContList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      }
    },
    // 获取供应商合同列表
    *fetchSuppContList({ payload }, { call, put }) {
      const response = yield call(getSuppContList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      }
    },
    // 获取待续签合同数量
    *fetchRenewalContNum({ payload, callback }, { call }) {
      const response = yield call(getCustContList, payload);
      if (response.success) {
        if (callback && typeof callback === 'function') {
          callback(response.data);
        }
      }
    },
    // 删除合同
    *delCont({ url, payload, callback }, { call }) {
      const response = yield call(delCont, url, payload);
      if (callback) callback(response);
    },
    // 更新合同状态
    *updateStatus({ url, payload, callback }, { call }) {
      const response = yield call(updateStatus, url, payload);
      if (callback) callback(response);
    },
    // 查询签署部门列表
    *fetchBaseDepart({ payload }, { call }) {
      const response = yield call(fetchBaseDepart, payload);
      return response;
    },
    // 获取签署人列表数据
    *queryUserList({ payload }, { call }) {
      const response = yield call(queryUserList, payload);
      return response;
    },
    // 客户合同管理提交数据
    customerSubmit:[
      function* ({ payload }, { call }) {
        const response = yield call(customerSubmit, payload);
        return response;
      },
      { type:'throttle',ms:10000 }
    ],
    // 客户管理 回显数据
    *getCustomerDetail({ payload }, { call, put }) {
      const response = yield call(getCustomerDetail, payload);
      if (response.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            contInfo: response.data,
          },
        });
      } else {
        message.warning(response.message || '回显数据：服务器端错误！');
      }
      return response;
    },
    // 客户合同管理 修改提交数据
    customerUpdateSubmit:[
      function* ({ payload }, { call }) {
      const response = yield call(customerUpdateSubmit, payload);
      return response;
    },
    { type:'throttle',ms:10000 }
  ],
    // 获取报价单列表数据
    *quotationList({ payload }, { call, put }) {
      const response = yield call(getQuotationList, payload);
      const {
        pageArg: { currentPage, pageSizes },
      } = payload;
      yield put({
        type: 'getQuoList',
        payload: {
          data: [],
          currentPage,
          pageSizes,
        },
      });
      if (response.success) {
        yield put({
          type: 'getQuoList',
          payload: {
            data: response.data,
            currentPage,
            pageSizes,
          },
        });
      } else {
        message.warning(response.message || '暂无数据：服务器端错误！');
      }
    },
    // 客户合同 获取历史记录列表
    *getHistoryList({ payload }, { call, put }) {
      const response = yield call(getHistoryList, payload);
      if (response.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            historyList: response.data,
          },
        });
      } else {
        message.warning(response.message || '历史记录数据：服务器端错误！');
      }
    },
    // 客户合同 历史记录详情数据
    *getHistoryDetail({ payload }, { call, put }) {
      const response = yield call(getHistoryDetail, payload);
      if (response.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            contInfo: response.data,
          },
        });
      } else {
        message.warning(response.message || '历史记录详情数据：服务器端错误！');
      }
      return response;
    },
    // 客户合同 续签提交接口
    custRenewSubmit:[
      function* ({ payload }, { call }) {
        const response = yield call(renewSubmit, payload);
        return response;
      },
      { type:'throttle',ms:10000 }
    ],
    // 供应商合同 获取供应商名称列表
    *getListByUser({ payload }, { call }) {
      const response = yield call(getListByUser, payload);
      return response;
    },
    // 供应商合同 已有客户 客户模糊搜索
    *getCustName({ payload }, { call }) {
      const response = yield call(getCustName, payload);
      return response;
    },
    // 供应商合同 新增客户，客户名称的搜索
    *getAddCustSearch({ payload }, { call }) {
      const response = yield call(getAddCustSearch, payload);
      return response;
    },
    // 供应商合同 新增客户，统一社会信用代码的搜索
    *getmdCustInfo({ payload }, { call }) {
      const response = yield call(getmdCustInfo, payload);
      return response;
    },
    // 供应商合同 新增客户提交数据
    *supplyInsert({ payload }, { call }) {
      const response = yield call(supplyInsert, payload);
      return response;
    },
    // 供应商合同 提交数据
    suppContSubmit:[
      function*({ payload }, { call }) {
      const response = yield call(suppContSubmit, payload);
      return response;
    },
    { type:'throttle',ms:10000 }
  ],
    // 供应商合同 回显数据
    *getSuppContDetail({ payload }, { call, put }) {
      const response = yield call(getSuppContDetail, payload);
      if (response.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            supplyInfo: response.data,
          },
        });
      } else {
        message.warning(response.message || '回显数据：服务器端错误！');
      }
      return response;
    },
    // 供应商合同 回显修改后的提交数据
    suppContUpdateSubmit:[
      function*({ payload }, { call }) {
        const response = yield call(suppContUpdateSubmit, payload);
        return response;
      },
      { type:'throttle',ms:10000 }
    ],
    // 供应商合同 历史记录列表数据接口
    *getSupplyHistoryList({ payload }, { call, put }) {
      const response = yield call(getSupplyHistoryList, payload);
      if (response.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            supplyHistoryList: response.data,
          },
        });
      } else {
        message.warning(response.message || '历史记录数据：服务器端错误！');
      }
    },
    // 供应商合同 历史记录详情数据接口
    *getHistorySupplyDetail({ payload }, { call, put }) {
      const response = yield call(getHistorySupplyDetail, payload);
      if (response.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            supplyInfo: response.data,
          },
        });
      } else {
        message.warning(response.message || '历史记录详情数据：服务器端错误！');
      }
      return response;
    },
    // 获取下载模板fileId fileName
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfo, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      } else {
        message.warning(`${response.message || '服务端错误：获取下载模板失败！'}`);
      }
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress:[
     function* ({ payload }, { call, put }) {
      try {
        const { tag, formData } = payload;
        let api;
        if (tag === 'ba') {
          api = baUploadFile;
        } else {
          api = sbUploadFile;
        }
        const response = yield call(api, formData);
        if (response.success) {
          yield put({
            type: 'setTempType',
            payload: { tempType: response.data && response.data.tempType },
          });
          // 不是100表示需要走队列
          if (response.data && response.data.successProp !== 100) {
            baSpType = tag;
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
            // 订阅成功后再触发进度条
            yield put({
              type: 'updateModalData',
              payload: { showProgress: true },
            });
          } else {
            yield put({
              type: 'handleBatchTask',
              payload: {
                ...response.data,
                baSpType: tag,
              },
            });
          }
        } else {
          message.warning(response.message || '上传文件错误：服务器端错误');
        }

        // 无需返回response对象
      } catch (e) {
        console.error(e);
      }
    },
    { type: 'throttle', ms: 10000 }
  ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.busicont);
      const { tempType } = state;
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          tempType,
        };
        if (payload.baSpType === 'ba') {
          resultInfo.errorUrl = '/csApi/custCont/dowoloadErrorExist';
        } else {
          resultInfo.errorUrl = '/csApi/suppCont/dowoloadErrorExist';
        }
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    // 获取所属客服列表
    *fetchRespUserList({ payload }, { call, put }) {
      const response = yield call(getRespUserList, payload);
      yield put({
        type: 'updateModalData',
        payload: {
          respUserList: [],
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateModalData',
          payload: {
            respUserList: Array.isArray(response.data) ? response.data : [],
          },
        });
      } else {
        message.warning(response.message || '获取所属客服数据：服务端错误');
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 更新数据 state
    updateModalData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 清除签署人
    updateClearData(state, { payload }) {
      const temp = state;
      temp.contInfo.signId = undefined;
      return {
        ...state,
        ...payload,
      };
    },
    // 字典转化
    matchDictName(
      state,
      {
        payload: { contInfo, dictCode },
      }
    ) {
      const posWayName = matchDict(dictCode.POS_WAY, contInfo.posWay) || '--';
      const billDelvDay =
        (contInfo.crmCustContConfig && contInfo.crmCustContConfig.billDelvDay) || '--';
      const payWayName =
        matchDict(
          dictCode.PAY_WAY,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.payWay
        ) || '--';
      const payPeriodName =
        matchDict(
          dictCode.CUST_PAY_PERIOD,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.payPeriod
        ) || '--';
      const invPeriodName =
        matchDict(
          dictCode.CUST_PAY_PERIOD,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.invPeriod
        ) || '--';
      const payoutDay =
        (contInfo.crmCustContConfig && contInfo.crmCustContConfig.payoutDay) || '--';
      const advancePrice =
        (contInfo.crmCustContConfig && contInfo.crmCustContConfig.advancePrice) || '--';
      const matColtWayName =
        matchDict(
          dictCode.SEND_MAT_COLT_WAY,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.invPeriod
        ) || '--';
      const invDelvTypeName =
        matchDict(
          dictCode.INV_DELV_TYPE,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.invDelvType
        ) || null;
      const invCateName =
        matchDict(
          dictCode.INV_CATE,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.invCate
        ) || null;
      const invTypeName =
        matchDict(
          dictCode.INV_TYPE,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.invType
        ) || null;
      const invDelvWayName =
        matchDict(
          dictCode.INV_DELV_WAY,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.invDelvWay
        ) || '--';
      const insFeeRuleName =
        matchDict(
          dictCode.FEE_RULE,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.insFeeRule
        ) || '--';
      const accuFeeRuleName =
        matchDict(
          dictCode.FEE_RULE,
          contInfo.crmCustContConfig && contInfo.crmCustContConfig.accuFeeRule
        ) || '--';
      const lowestPrice =
        (contInfo.crmCustContConfig && contInfo.crmCustContConfig.lowestPrice) || '--';
      const fullyFlag =
        (contInfo.crmCustContConfig && contInfo.crmCustContConfig.fullyFlag) || null;
      const collTax = (contInfo.crmCustContConfig && contInfo.crmCustContConfig.collTax) || '--';
      const splitFlag = (contInfo.crmCustContConfig && contInfo.crmCustContConfig.splitFlag) || [];
      const paidFlag = (contInfo.crmCustContConfig && contInfo.crmCustContConfig.paidFlag) || [];
      const selectionTypeName =
        matchDict(
          dictCode.SELECTION_TYPE,
          contInfo.defaultAccoPeriod && contInfo.defaultAccoPeriod.selectionType
        ) || '--';
      const speReq = (contInfo.crmCustContConfig && contInfo.crmCustContConfig.speReq) || null;
      return {
        ...state,
        contInfo: {
          ...contInfo,
          posWayName,
          crmCustContConfig: {
            payWayName,
            billDelvDay,
            payPeriodName,
            invPeriodName,
            payoutDay,
            advancePrice,
            matColtWayName,
            invDelvTypeName,
            invCateName,
            invTypeName,
            invDelvWayName,
            insFeeRuleName,
            accuFeeRuleName,
            lowestPrice,
            fullyFlag,
            collTax,
            splitFlag,
            paidFlag,
            speReq,
          },
          selectionTypeName,
        },
      };
    },
    // 报价单列表
    getQuoList(
      state,
      {
        payload: { data, currentPage, pageSizes },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageQuoData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize: pageSizes },
        },
      };
    },
    // 供应商合同字典转化
    matchDictSupplyName(
      state,
      {
        payload: { supplyInfo, dictCode },
      }
    ) {
      const posWayName = matchDict(dictCode.POS_WAY, supplyInfo.posWay) || '--';
      const payWayName =
        matchDict(
          dictCode.PAY_WAY,
          supplyInfo.crmCustContConfig && supplyInfo.crmCustContConfig.payWay
        ) || '--';
      const billDelvDay =
        (supplyInfo.crmCustContConfig && supplyInfo.crmCustContConfig.billDelvDay) || '--';
      const invPeriodName =
        matchDict(
          dictCode.CUST_PAY_PERIOD,
          supplyInfo.crmCustContConfig && supplyInfo.crmCustContConfig.invPeriod
        ) || '--';
      const insFeeRuleName =
        matchDict(
          dictCode.FEE_RULE,
          supplyInfo.crmCustContConfig && supplyInfo.crmCustContConfig.insFeeRule
        ) || '--';
      const accuFeeRuleName =
        matchDict(
          dictCode.FEE_RULE,
          supplyInfo.crmCustContConfig && supplyInfo.crmCustContConfig.accuFeeRule
        ) || '--';
      const speReq = (supplyInfo.crmCustContConfig && supplyInfo.crmCustContConfig.speReq) || null;
      const custList = supplyInfo.custList || [];
      const fileList = supplyInfo.fileList || [];
      return {
        ...state,
        supplyInfo: {
          ...supplyInfo,
          posWayName,
          crmCustContConfig: {
            payWayName,
            billDelvDay,
            invPeriodName,
            insFeeRuleName,
            accuFeeRuleName,
            speReq,
          },
          custList,
          fileList,
        },
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    setTempType(state, { payload }) {
      return {
        ...state,
        tempType: payload.tempType,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: {
                  ...action.data,
                  baSpType,
                },
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};

export default ModelAddEmp;
